package com.gulimall.search.web;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author coder_ccy
 * @date 2022/3/30 11:37
 * 线程通讯
 * 生成者 ：存数据   线程
 * 消费者： 取数据
 * 仓库：   数据   线程安全  加锁
 *
 * 模拟传感器收集数据：  传感器   1   收集器
 *
 */
public class Demo2 {

    public static void main(String[] args) {
        Stock stock = new Stock();

        new Productor("生产者1",stock).start();
        new Productor("生产者2",stock).start();
        new Productor("生产者3",stock).start();

        new Consumer("消费1",stock).start();
        new Consumer("消费2",stock).start();
    }

    public static void print(String str) throws IOException {  // 1. 能追加   2. 能换行
        FileWriter fileWriter = new FileWriter(new File("d:/console.txt"),true);
        BufferedWriter writer = new BufferedWriter(fileWriter);

        writer.write(str);
        writer.newLine();

        writer.flush();
        writer.close();
        fileWriter.close();

    }
}

class Productor extends Thread{

    private Stock stock;

    public Productor(String proName,Stock stock){
        super(proName);
        this.stock = stock;
    }

    @Override
    public void run() {
        while(true){
            try {
                stock.product();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer extends Thread{

    private Stock stock;

    public Consumer(String proName,Stock stock){
        super(proName);
        this.stock = stock;
    }

    @Override
    public void run() {
        while (true){

            try {
                stock.consume();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class Stock{
    int num = 0;   //10个存满

    public synchronized void product() throws IOException {//生产商品  锁  this

        while(num>=10){  //放满了，不能生成，在这里等待
            try {
                this.wait();  //阻塞
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        num++;
        Demo2.print(Thread.currentThread().getName()+" 生成了第"+num+"个商品");
        this.notifyAll(); //唤醒


    }

    public synchronized void consume() throws IOException {//消费商品  this

        while(num<=0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        Demo2.print(Thread.currentThread().getName()+" 消费了第"+num+"个商品");
        num--;
        this.notifyAll();

    }


}
